<template>
  <div class="markdown-container">
    <!-- 渲染区 -->
    <div id="markdown-box"></div>
    <div class="bottom">
      <el-button type="primary" @click="onSubmitClick">{{
        $t('message.article.commit')
      }}</el-button>
    </div>
  </div>
</template>

<script setup>
import MkEditor from '@toast-ui/editor'
import '@toast-ui/editor/dist/toastui-editor.css'
import '@toast-ui/editor/dist/i18n/zh-cn'
import store from '@/store'
import { onMounted, defineProps, defineEmits, watch } from 'vue'
import { watchLangChange } from '@/utils/i18n'
import { articleCreate, articleEditor } from './commit'
const props = defineProps({
  title: {
    type: String,
    required: true
  },
  details: {
    type: Object,
    required: true
  }
})
const emits = defineEmits(['onSuccess'])
let mkEditor
let el
onMounted(() => {
  el = document.getElementById('markdown-box')
  initEditor()
})
const initEditor = () => {
  mkEditor = new MkEditor({
    el,
    height: '500px',
    previewStyle: 'vertical',
    language: store.getters.lang === 'en' ? 'en' : 'zh-CN'
  })
  mkEditor.getMarkdown()
}
watchLangChange(() => {
  if (!el) return
  const htmlStr = mkEditor.getHTML()
  mkEditor.destroy()
  initEditor()
  mkEditor.setHTML(htmlStr)
})
const onSubmitClick = async () => {
  if (JSON.stringify(props.details) === '{}') {
    await articleCreate({
      title: props.title,
      content: mkEditor.getMarkdown()
    })
  } else {
    await articleEditor({
      title: props.title,
      content: mkEditor.getMarkdown(),
      id: props.details._id
    })
  }

  mkEditor.reset()
  emits('onSuccess')
}
watch(
  () => props.details,
  () => {
    if (JSON.stringify(props.details) === '{}') return
    mkEditor.setMarkdown(props.details.content)
  },
  {
    immediate: true
  }
)
</script>

<style lang="scss" scoped>
.markdown-container {
  .bottom {
    margin-top: 20px;
    text-align: right;
  }
}
</style>
